package com.gy.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.gy.constant.RedisConstants;
import com.gy.controller.common.UserHolder;
import com.gy.vo.UserLoginVO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class CustomTokenFilter extends OncePerRequestFilter {

    private final StringRedisTemplate stringRedisTemplate;

    public CustomTokenFilter(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            chain.doFilter(request, response);
            return;
        }

        String redisKey = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(redisKey);
        if (userMap.isEmpty()) {
            chain.doFilter(request, response);
            return;
        }

        UserLoginVO userVo = BeanUtil.fillBeanWithMap(userMap, new UserLoginVO(), false);

        // 关键修改：传入空的权限列表（而非null），确保isAuthenticated()返回true
        List<GrantedAuthority> authorities = new ArrayList<>(); // 空权限列表
        UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                userVo, null, authorities); // 第三个参数为非null的权限列表

        authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authToken);

        UserHolder.saveUser(userVo);
        chain.doFilter(request, response);
    }
}
